package com.soft.controller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.soft.entity.User;
import com.soft.service.MetricsService;
import com.soft.service.UserService;

import jakarta.servlet.http.HttpServletRequest;
/**
 * 指标接口（/metrics）：
 * - /leader：团队/项目负责人视角，需 X-User-Id
 * - /admin：管理员视角，需 admin 权限
 */
@RestController
@RequestMapping("/metrics")
public class MetricsController {
    private static final Logger log = LoggerFactory.getLogger(MetricsController.class);

    @Autowired
    private MetricsService metricsService;

    @Autowired
    private UserService userService;

    private Integer currentUserId(HttpServletRequest req) {
    // 从请求头读取伪登录用户ID（演示环境使用），生产应改为真实鉴权
    if (req == null) return null;
    String h = req.getHeader("X-User-Id");
    if (h == null || h.isEmpty()) return null;
    try { return Integer.valueOf(h); } catch (NumberFormatException ex) { return null; }
    }

    private boolean isAdmin(HttpServletRequest req) {
    // 简单判断用户角色是否为 admin，用于保护管理员接口
    Integer uid = currentUserId(req);
    if (uid == null) return false;
    User u = userService.getById(uid);
    return u != null && u.getRole() != null && "admin".equalsIgnoreCase(u.getRole());
    }

    // 项目/团队领导视角：统计其作为 leader 的团队范围内的汇总
    @GetMapping("/leader")
    public ResponseEntity<?> leader(@RequestParam(value = "days", required = false, defaultValue = "7") Integer days,
                                    HttpServletRequest req) {
        try {
            // 1) 获取当前用户ID并做未登录校验
            Integer uid = currentUserId(req);
            if (uid == null) return ResponseEntity.status(401).body("unauthorized");
            // 2) days 做下限保护，避免0/负数
            Map<String, Object> data = metricsService.leaderMetrics(uid, days != null ? Math.max(1, days) : 7);
            return ResponseEntity.ok(data);
        } catch (Exception e) {
            log.error("/metrics/leader error", e);
            return ResponseEntity.status(500).body("leader metrics failed: " + e.getMessage());
        }
    }

    // 管理员视角：全公司汇总（需 admin）
    @GetMapping("/admin")
    public ResponseEntity<?> admin(@RequestParam(value = "days", required = false, defaultValue = "7") Integer days,
                                   HttpServletRequest req) {
        try {
            // 1) 校验是否管理员
            if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
            // 2) days 下限保护并查询
            Map<String, Object> data = metricsService.adminMetrics(days != null ? Math.max(1, days) : 7);
            return ResponseEntity.ok(data);
        } catch (Exception e) {
            log.error("/metrics/admin error", e);
            return ResponseEntity.status(500).body("admin metrics failed: " + e.getMessage());
        }
    }
}
